<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

// 优惠券控制
class Coupon extends Common
{
    // 优惠券列表
    public function getCouponList()
    {

        $this->CouponList();

       return  $this->fetch('coupon/index');
    }

    private function CouponList()
    {

        $where['is_del'] = 0;

        $list = Db::table('coupon')->where($where)->paginate(10);
        $coupon_amount = Db('coupon')->where($where)->count();
        $page = $list->render();

        $oneday = 24 * 3600;
        $list = $list->items();
        foreach ($list as $key => $value) {

            $list[$key]['expire'] = ($list[$key]['expire'] / $oneday) .' 天 ';
        }


        $this->assign('coupon_amount', $coupon_amount);
        $this->assign('page', $page);
        $this->assign('list', $list);
    }

    // 新增优惠券种类
    public function getCouponAdd(){

        return $this->fetch('coupon/add');
    }

    public function postCouponAdd(){

        $amount= input('post.amount');
        if(!$amount){
            $this->error('总金额不能为空', '/coupon/CouponAdd');
        }
        $discount = input('post.discount');
        if (!$amount) {
            $this->error('折扣金额不能为空', '/coupon/CouponAdd');
        }
        $expire = input('post.expire',7); //默认优惠券 7 天内有效

        $available = input('post.available');
       
        $res= \app\admin\model\CouponModel::couponAdd($amount, $discount, $expire, $available);

        if($res){
            $this->success('添加成功', '/coupon/CouponList');
        }else{
            $this->error('添加失败', '/coupon/CouponList');
        }


    }

    // 删除优惠券 
    public function postCouponDel(){
        $id = input('post.id');

        $res = \app\admin\model\CouponModel::delCoupon($id);

        return $res;
    }

    // Ajax 切换
    public function postAjaxWithdrawGoods()
    {
        $request = request();

        if ($request->isAjax()) {
            $available = $request->param('available');
            $coupon_id = $request->param('coupon_id');



            $res =  \app\admin\model\CouponModel::updateCouponStatus($available, $coupon_id);

            return $res;

        } else {
            return false;
        }
    }

    // 查看用户持有优惠券列表
    public function getUserOwnCoupon()
    {
        // return $this->fetch('coupon/UserOwnCoupon');
    }



}
